import { CondintionType, IConditions, IStatePool, IStatePoolItem, StateType } from './type';


const createStatePool = () => {

  const statePool: ({[name in StateType]: IStatePool}) = {
    success: {},
    error: {},
    warn: {},
  };
  const STATE_POOL_KEYS = Object.keys(statePool);

  const updateState = (key: string, state: StateType, msg: string = '') => {
    
    if (statePool[state][key]) {
      statePool[state][key].updateTime = Date.now();
      ++statePool[state][key].count;
      statePool[state][key].is = true;
      statePool[state][key].msgList.push(msg);
    } else {
      statePool[state][key] = {
        count: 1,
        updateTime: Date.now(),
        is: true,
        msgList: [msg],
      }
    }
    STATE_POOL_KEYS.forEach((stateName) => {
      const name = stateName as StateType;
      stateName !== state && statePool[name][key] && (statePool[name][key].is = false);
    });
  };

  const findState = (key: string, state: StateType): IStatePoolItem => {
    return statePool[state][key];
  }

  
  const judgeCondition = (conditions: IConditions | undefined): boolean => {
    if (conditions) {
      
      return judge(conditions.conditionList, conditions.type);
    } else {
      return true;
    }
  };

  const judge = (list: { key: string, state: StateType, is: boolean }[], type: CondintionType): boolean => {
    switch(type) {
      case 'every':
        return list.every(({key, state, is}) => findState(key, state).is === is);
      case 'some':
        return list.some(({key, state, is}) => findState(key, state).is === is);
    }
  }

  return {
    updateState,
    findState,
    judgeCondition,
  };
};

export {
  createStatePool,
};
